﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Microsoft.SharePoint;
using Eneta.Portal.Common.Repository;

namespace Eneta.Portal.Profiles.Controls
{
    public class ProfileLiteratureListControl : UserControl
    {
        private IList<LiteratureDto> _literatureItems;
        public string LiteratureType { get; set; }
        private IList<LiteratureDto> Items
        {
            get
            {
                if (_literatureItems == null)
                    return new List<LiteratureDto>();
                return _literatureItems;
            }
            set
            {
                if (value == null)
                {
                    Logger.LogInfo("_literatureItems collection is null", "ProfileLiteratureListControl.Items");
                    _literatureItems = new List<LiteratureDto>();
                }
                else if (value.Count == 0)
                {
                    Logger.LogInfo("_literatureItems collection count is 0", "ProfileLiteratureListControl.Items");
                    _literatureItems = new List<LiteratureDto>();
                }
                else
                {
                    Logger.LogInfo("_literatureItems collection is set", "ProfileLiteratureListControl.Items");
                    _literatureItems = value;
                }
            }
        }

        private bool IsAdmin
        {
            get
            {
                var user = SPContext.Current.Web.CurrentUser;
                if (user == null)
                    return false;
                if (user.IsSiteAdmin)
                    return true;
                return false;
            }
        }
        private bool IsProfileOwner { get; set; }

        protected Repeater LiteratureRepeater;
        protected HtmlGenericControl LiteratureBlockTitle;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            LiteratureRepeater.ItemDataBound += LiteratureRepeater_ItemDataBound;
        }

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                base.OnLoad(e);
                if (!IsPostBack)
                {
                    var repository = new LiteratureRepository(SPContext.Current.Web);
                    var profile = EnetaProfilePage.GetCurrentProfile();
                    if (profile == null)
                    {
                        Logger.LogInfo("User profile is not found", "ProfileLiteratureListControl_OnLoad");
                        return;
                    }
                    string webUrl = GetLiteratureWebUrl();
                    if (string.IsNullOrEmpty(webUrl))
                    {
                        Logger.LogInfo("Literature web url is not found", "ProfileLiteratureListControl_OnLoad");
                        return;
                    }
                    try
                    {

                        var user = GetProfileUser(profile.LiveIdToken);
                        var currentUser = SPContext.Current.Web.CurrentUser;
                        if (currentUser != null)
                        {
                            if (currentUser.LoginName == string.Format("liveid:{0}", profile.LiveIdToken))
                            {
                                IsProfileOwner = true;
                            }
                        }
                        if (IsAdmin || IsProfileOwner)
                        {
                            Items = repository.GetUserLiteratureItems(webUrl, LiteratureType, user.ID, false);
                        }
                        else
                        {
                            Items = repository.GetUserLiteratureItems(webUrl, LiteratureType, user.ID, true);
                        }
                        if (Items.Count != 0)
                        {

                            if (LiteratureBlockTitle != null)
                            {
                                LiteratureBlockTitle.InnerText = GetBlockTitle();
                            }

                            LiteratureRepeater.DataSource = Items;
                            LiteratureRepeater.DataBind();
                        }
                        else
                        {
                            this.Visible = false;
                            LiteratureRepeater.Visible = false;
                        }
                    }
                    catch (ArgumentNullException ex)
                    {
                        Logger.LogException(ex);
                        return;
                    }
                    catch (SPException ex)
                    {
                        Logger.LogException(ex);
                        return;
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        private SPUser GetProfileUser(string profileId)
        {
            var web = SPContext.Current.Web;
            var userId = string.Format("liveid:{0}", profileId);
            SPUser user = null;
            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (SPSite site = new SPSite(web.Site.ID))
                    {
                        using (SPWeb currentWeb = site.OpenWeb(web.ID))
                        {
                            user = currentWeb.SiteUsers[userId];
                        }
                    }
                });
            return user;
        }

        protected void LiteratureRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var resultItem = e.Item.DataItem as LiteratureDto;

            if (e.Item.DataItem == null)
                return;
            
            if (!IsAdmin && !IsProfileOwner)
            {
                ShowAnonymousUserData(e.Item, resultItem);
            }
            else if (IsAdmin || IsProfileOwner)
            {
                var moderationStatus = e.Item.FindControl("ModerationStatus") as HtmlGenericControl;
                if (moderationStatus != null)
                {
                    var moderationStatusComment = e.Item.FindControl("ModerationStatusComment") as HtmlGenericControl;
                    var status = GetModerationStatus(resultItem.Status);
                    moderationStatus.InnerText = status;
                    if (status == "Kinnitatud")
                    {
                        moderationStatus.Style.Add("color", "green");
                        moderationStatus.Style.Add("font-style", "Italic");
                    }
                    else if (status == "Tagasilükatud")
                    {
                        moderationStatus.Style.Add("color", "red");
                        moderationStatus.Style.Add("font-style", "Italic");
                    }
                    else
                    {
                        moderationStatus.Style.Add("color", "#ffcc00");
                        moderationStatus.Style.Add("font-style", "Italic");
                    }
                    if (moderationStatusComment != null)
                    {
                        if (!string.IsNullOrEmpty(resultItem.StatusComment))
                        {
                            moderationStatusComment.InnerText = string.Format("({0})", resultItem.StatusComment);
                        }
                    }
                }
                ShowAdministrationData(e.Item, resultItem);
            }
        }

        private string GetBlockTitle()
        {
            string title = string.Empty;
            if (IsProfileOwner)
            {
                title = "Minu";
            }
            if (LiteratureType == "Ajakiri")
            {
                if (!string.IsNullOrEmpty(title))
                {
                    title += " ajakirjad";
                }
                else
                {
                    title = "Ajakirjad";
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(title))
                {
                    title += " raamatud";
                }
                else
                {
                    title = "Raamatud";
                }
            }
            return title;
        }

        private string GetModerationComment(object sender)
        {
            var button = sender as Button;
            var comment = string.Empty;
            if (button != null)
            {
                var parent = button.Parent as RepeaterItem;
                if (parent != null)
                {
                    var commentControl = parent.FindControl("RejectReasonField") as TextBox;
                    if (commentControl != null)
                    {
                        comment = commentControl.Text;
                    }
                }
            }
            return comment;
        }
       
        /* Item moderation method
        private void ModerateItem(int itemId, SPModerationAction moderationAction, string comment)
        {
            var repository = new LiteratureRepository(SPContext.Current.Web);
            var webUrl = GetLiteratureWebUrl();
            if (string.IsNullOrEmpty(webUrl))
            {
                Logger.LogInfo("Literature web url is missing", "ProfileLiteratureListControl_ModerateItem");
            }
            else
            {
                if (moderationAction == SPModerationAction.Approve)
                {
                    repository.ApproveBook(itemId, webUrl, comment);
                } else if (moderationAction == SPModerationAction.Reject) {
                    repository.DenieBook(itemId, webUrl, comment);
                }
            }
             
        }
        */

        private void SetGenericData(RepeaterItem item, LiteratureDto dto)
        {

            var LiteratureTitle = item.FindControl("LiteratureTitle") as HtmlAnchor;
            var contentType = item.FindControl("ContentType") as HtmlGenericControl;
            
            if (contentType != null)
            {
                contentType.InnerText = dto.LastModified.ToShortDateString();
            }
            if (LiteratureTitle != null)
            {
                LiteratureTitle.HRef = dto.ItemUrl;
                LiteratureTitle.InnerText = dto.Title;
                LiteratureTitle.Title = dto.Title;
            }
            
        }

        private void ShowAdministrationData(RepeaterItem item, LiteratureDto dto)
        {
            SetGenericData(item, dto);
            //TODO: Add item administration options (approval, rejection, editing)
            
        }

        private void ShowAnonymousUserData(RepeaterItem item, LiteratureDto dto)
        {
            SetGenericData(item, dto);
        }

        private string GetModerationStatus(SPModerationStatusType moderationStatus)
        {
            switch (moderationStatus)
            {
                case SPModerationStatusType.Approved:
                    return "Kinnitatud";
                case SPModerationStatusType.Denied:
                    return "Tagasilükatud";
                case SPModerationStatusType.Pending:
                    return "Kinnitamisel";
                default: return string.Empty;
            }
        }

        private string GetLiteratureWebUrl()
        {
            Logger.LogInfo("valime kirjanduse url-i", "ProfileLiteratureListControl_GetLiteratureWebUrl");
            switch (LiteratureType)
            {
                case "Raamat":
                    return "/oppimine/raamatud";
                case "Ajakiri":
                    return "/oppimine/ajakirjad";
                default:
                    return string.Empty;
            }
        }
    }
}
